package machine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;

public final class Instructions extends ArrayList<Instruction> {
	private HashMap hm = new HashMap();
	
	public void addFunction(String s, int i) {
		hm.put(s, i);
		functionName2lineNumber();
	}
	
	@Override
	public boolean add(Instruction i) {
		boolean b = super.add(i);
		if (i.hasString()) {
			functionName2lineNumber();
		}
		return b;
	}
	
	private void functionName2lineNumber() {
		Iterator it = hm.entrySet().iterator();
		while(it.hasNext()) {
			Map.Entry pairs = (Map.Entry)it.next();
		 
	        Iterator it2 = this.iterator();
	        while (it2.hasNext()) {
	        	Instruction inst = (Instruction)it2.next();
	        	inst.replace((String)pairs.getKey(), (Integer)pairs.getValue());
	        }
		}
	}
	
	public String toString() {
		String str	= "............" 
					+ "Instructions" 
					+ "............";
		int count = 0;
		for(Instruction inst : this) {
			str += "\n" + "(" + count + ")" + inst;
			count++;
		}
		str += "\n....................................";

		return str;
	}
	
}